<template>
  <view class="cart">
    <!-- 滑动区域 -->
    <scroll-view class="scroll-view" scroll-x="true" scroll-y="false">
      <view class="c">
        <view class="list" v-for="(item, index) in list" :key='index'>
          <view class="l">
            <!-- 列表的复选框 -->
           <view
             :class="{'custom-checked': item.isChecked, 'custom-unchecked': !item.isChecked}"
             @click="toggleCheck(item.cartItemId)"
             style=" display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            border-radius: 5px;
            border: 1px solid #ccc;"
           >
             <view class="checkbox-icon">
               <text v-if="item.isChecked">✔️</text>
               <text v-else></text>
             </view>
           </view>

            <image :src="item.imageUrl" mode="" class="img" @click="gotoProductDetail(item.productId)"></image>
          </view>
          <view class="center">
            <view class="name">
              {{item.name}}
            </view>
            <view class="size">
              规格：{{item.skuName}}
            </view>
            <view class="count">
              数量：x{{item.quantity}}
            </view>
            <view class="time">
              时间：{{item.addTime}}
            </view>
          </view>
          <view class="r">
            <!-- 商品小计 -->
            <view class="price"> {{ item.price.toFixed(2) }}元 </view>
            <view class="update-count">
              <view class="reduce" @tap="reduce(item.cartItemId)">
                -
              </view>
              <view class="cart-count">
                {{item.quantity}}
              </view>
              <view class="add" @tap="add(item.cartItemId)">
                +
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部导航栏 -->
    <view class="tabbar">
      <view class="all">
        <view
          :class="{'all-checked': isAllChecked, 'all-unchecked': !isAllChecked}"
          @click="toggleAllCheck"
          style="
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            border-radius: 5px;
            border: 1px solid #ccc;
          "
        >
          <!-- 模拟选中和未选中状态 -->
          <text v-if="isAllChecked" style="color: #ffffff;">✔️</text>
        </view>

        全选
      </view>
      <view class="totalPrice">
        总价:{{cartTotalPrice}}元
      </view>
      <view class="submitOrder" @tap="submitOrder">
        付款
      </view>
      <view class="submitOrder" @tap="submitOrder">
        删除
      </view>
    </view>
  </view>
</template>

<script>
import { getCart, getStock, deleteById, updateQuantity,update } from '@/api/cart/cart.js';
import { getProductDetail } from '../../../api/productDetail/productDetail.js';

export default {
  data() {
    return {
      list: [],
      userId: null,
      tmp: [],
      previousList: [] // 用于存储上一次的 list 状态
    };
  },
  computed: {
    isAllChecked: {
      get() {
        return this.list.every(el => el.isChecked === true);
      },
      set(val) {
        this.list.forEach(el => el.isChecked = val);
      }
    },
    cartTotalPrice() {
      let sum = 0;
      this.list.forEach(el => {
        if (el.isChecked) {
          sum += el.price;
        }
      });
      return sum;
    }
  },
  methods: {
	  async updateQuantity(cartItemId, quantity){
		  console.log("-------"+cartItemId+"--------"+quantity)
		 await update(cartItemId,quantity)
	  },
    async delete(ids) {
      await deleteById(ids);
    },
    async getStockById(id) {
      return await getStock(id);
    },
    async getProduct() {
      try {
        const data = await getCart(this.userId);
        this.tmp = await Promise.all(
          data.map(async (order) => {
            const productDetail = await this.fetchProductDetail(order.productId);
            const stock = await this.getStockById(order.skuId);
            return {
              ...order,
              stock: stock.stock,
              productId: productDetail.productId,
              name: productDetail?.productName || '未知商品',
              imageUrl: this.getPrimaryImageUrl(productDetail?.images || []),
              price: productDetail.price * order.quantity,
              dj: productDetail.price,
              isChecked: false // 初始化为 false
            };
          })
        );
        this.list = this.tmp;
        this.previousList = JSON.parse(JSON.stringify(this.list)); // 初始化 previousList
      } catch (e) {
        console.log(e);
      }
    },
    async fetchProductDetail(productId) {
      try {
        const productDetail = await getProductDetail(productId);
        return productDetail;
      } catch (error) {
        console.error("获取商品详情失败:", error);
        return null;
      }
    },
    getPrimaryImageUrl(images) {
      if (images && images.length > 0) {
        const primaryImage = images.find((image) => image.isPrimary);
        return primaryImage
          ?primaryImage.imageUrl
          : images[0].imageUrl;
      }
      return require('@/static/fss-image/lunbotu1.png');
    },
    gotoProductDetail(productId) {
      wx.navigateTo({
        url: `/pages/product/detail/detail?productID=${productId}`
      });
    },
    toggleCheck(id) {
      this.list.forEach(el => {
        if (el.cartItemId === id) {
			  console.log(el.isChecked)
          el.isChecked = !el.isChecked;
		  console.log(el.isChecked)
        }
      });
    },
    toggleAllCheck() {
      this.isAllChecked = !this.isAllChecked;
    },
    add(id) {
      this.list.forEach(el => {
        if (el.cartItemId === id) {
          if (el.quantity < el.stock) {
            el.quantity++;
            el.price = el.quantity * el.dj;
          } else {
            uni.showToast({
              title: '库存不足哦~',
              icon: 'none'
            });
          }
        }
      });
    },
    reduce(id) {
      this.list.forEach(el => {
        if (el.cartItemId === id) {
          if (el.quantity > 1) {
            el.quantity--;
            el.price = el.quantity * el.dj;
          } else {
            uni.showToast({
              title: '至少购买一件商品哦',
              icon: 'none'
            });
          }
        }
      });
    },
    submitOrder() {
      const bol = this.list.every(el => el.isChecked === false);
      if (bol) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        });
      } else {
        const cartList = this.list.filter(el => el.isChecked);
        const ids = cartList.map(el => el.cartItemId);
        console.log(ids);
        this.delete(ids).then(() => {
          this.list = this.list.filter(item => !ids.includes(item.cartItemId));
        });
        cartList.totalPrice = this.cartTotalPrice;
        console.log(this.list);
		setTimeout(() => {
		  uni.redirectTo({
		    url: `/pages/product/confirm/pay`,
		  });
		}, 1000);
      }
    }
  },
watch: {
  list: {
    deep: true,
    handler(newList, oldList) {
		// console.log(newList)
		// console.log(oldList)
      newList.forEach((newItem, index) => {
        const oldItem = this.previousList[index];
		console.log(newItem)
		console.log(oldItem)
        if (newItem.quantity !== oldItem.quantity) {
          // 调用后端接口更新数量
          this.updateQuantity(newItem.cartItemId, newItem.quantity)
            .then(response => {
              console.log('数量更新成功:', response);
            })
            .catch(error => {
              console.error('数量更新失败:', error);
            });
        }
      });
      this.previousList = JSON.parse(JSON.stringify(newList)); // 更新 previousList
    }
  }
},
  onLoad() {
    if (!this.userId) {
      this.$store
        .dispatch('GetInfo')
        .then(() => {
          this.userId = this.$store.state.user.userId;
          console.log("用户ID:", this.userId);
          this.getProduct();
        })
        .catch((error) => {
          console.error("获取用户信息失败:", error);
        });
    } else {
      this.getProduct();
    }
  }
};
</script>


<style lang="scss" scoped>
page {
  background: #f1e8e7;
}

// 滑动区域
.scroll-view {
  width: 100%;
  height: 80%;
  white-space: nowrap;
  margin-bottom: 500rpx;
   padding-left: 30rpx;// 为底部导航栏留出空间
}

.c {
  width: 670rpx;
  margin: 0 auto;
  display: inline-block; // 使商品卡片水平排列
}

// 居中显示
@mixin textCenter {
  display: flex;
  align-items: center;
  justify-content: center;
}

.list {
  width: 700rpx;//672
  height: 240rpx;//208
  background: #f9f9f9;
  box-shadow: 0 8rpx 16rpx 0 rgba(83, 66, 49, 0.08);
  border-radius: 24rpx;
  margin-top: 32rpx;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .l {
    display: flex;
    align-items: center;
    .checkbox {
      margin-right: 10rpx;
    }
    .img {
      width: 136rpx;
      height: 136rpx;
      background-color: pink;
      margin-left: 10rpx;
      border-radius: 8%;
    }
  }
  .center {
    width: 170rpx;
    .name {
      font-size: 26rpx;
      color: #3E3E3E;
      letter-spacing: 1.86rpx;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .size {
      font-size: 22rpx;
      color: #8D8D8D;
      letter-spacing: 1.57rpx;
    }
    .count {
      font-size: 22rpx;
      color: #8D8D8D;
      letter-spacing: 1.57rpx;
    }
  }
  .r {
	  margin-top: 40rpx;//40
    .price {
      margin-top: 40rpx;
      font-size: 26rpx;
      color: red;
      letter-spacing: 0;
      margin-left: 40rpx;
    }
    // 加减数量
    .update-count {
      margin-top: 40rpx;
      display: flex;
      .reduce {
        width: 40rpx;
        height: 40rpx;
        background: #F1ECE7;
        border-radius: 21.6rpx;
        color: #979797;
        @include textCenter;
        font-size: 50rpx;
      }
      .add {
        width: 40rpx;
        height: 40rpx;
        background: #F1ECE7;
        border-radius: 21.6rpx;
        color: #979797;
        @include textCenter;
        font-size: 40rpx;
      }
      .cart-count {
        width: 72rpx;
        height: 40rpx;
        background: #F1ECE7;
        border-radius: 21.6rpx;
        margin-left: 18rpx;
        margin-right: 18rpx;
        text-align: center;
        line-height: 40rpx;
      }
    }
  }
}
.time {
  font-size: 22rpx;
  color: #8D8D8D;
  letter-spacing: 1.57rpx;
}

// 底部导航
.tabbar {
  width: 100%;
  height: 176rpx;
  background-color: #ffffff;
  position: fixed;
  bottom: 0rpx;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border-radius: 8% 8%;
  .all {
    font-size: 32rpx;
    color: #3E3E3E;
    letter-spacing: 2.29rpx;
    display: flex;
    align-items: center;
    .checkbox {
      margin-right: 10rpx;
    }
  }

  .totalPrice {
    font-size: 32rpx;
    color: #3E3E3E;
    letter-spacing: 2.29rpx;
    color: red;
  }

  .submitOrder {
    width: 208rpx;
    height: 80rpx;
    background: #354E44;
    border-radius: 14rpx;
    font-size: 36rpx;
    color: #FFFFFF;
    letter-spacing: 2.57rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}.custom-checked {
	width: 50rpx;
	height: 50rpx;
  background-color: #ffaa00; /* 选中时的背景颜色 */
  color: #005500;
}

.custom-unchecked {
  background-color: #ffffff; /* 未选中时的背景颜色 */
	width: 50rpx;
	height: 50rpx;	width: 50rpx;
	height: 50rpx;
  color: #005500;
}
.all-checked {
	width: 50rpx;
	height: 50rpx;	width: 50rpx;
	height: 50rpx;	width: 50rpx;
	height: 50rpx;
  background-color: #ffaa00; /* 选中时背景颜色 */
  border-color: #ffaa00;
}

.all-unchecked {
	width: 50rpx;
	height: 50rpx;
  background-color: #ffffff; /* 未选中时背景颜色 */
  border-color: #ccc;
}

</style>
